﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QueuesAndStacks.DecodeString
{
    class MainProject
    {
        static void Main(string[] args)
        {
            int[] nums = new int[] { 73, 74, 75, 71, 69, 72, 76, 73 };
            Console.WriteLine(DecodeString("abc3[cd]xyz"));
            Console.ReadKey();
        }

        public static string DecodeString(string s)
        {
            string str = string.Empty;
            Stack<char> stack = new Stack<char>();
            foreach (var item in s)
            {
                if (item == ']')
                {
                    string temp = string.Empty;
                    while (stack.Count>0&&stack.Peek() != '[') temp = stack.Pop().ToString() + temp;
                    stack.Pop();
                    string numStr = string.Empty;
                    while (stack.Count > 0 && stack.Peek() >= 48 && stack.Peek() <= 57) numStr = stack.Pop().ToString() + numStr;
                    int num = int.Parse(numStr);
                    string temp2 = string.Empty;
                    for (int i = 0; i < num; i++) temp2 = temp + temp2;
                    foreach (var item1 in temp2) stack.Push(item1);
                }
                else
                {
                    stack.Push(item);
                }
            }
            foreach (var item in stack)
            {
                str = item + str;
            }
            return str;
        }
    }
}
